package com.ling.service;

import com.ling.dao.UserDao;
import com.ling.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * @author 编程之外
 * @company lingStudy
 * @create 2020-07-09 15:34
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    //用户注册
    @Override
    public void saveUser(User user) {
        //0.根据前端输入的用户名，判断用户是否已存在
        User byUserName = userDao.findByUserName(user.getUsername());
        if (byUserName==null){
            //1.设置用户注册时间
            user.setRegistertime(new Date());
            //2.生成用户状态
            user.setState(false);
            //3.调用dao
            userDao.saveUser(user);
        }else {
            throw new RuntimeException("该用户已存在！");
        }

    }

    //登录
    @Override
    public User login(User user) {
        //1.根据前端输入的用户名，判断用户是否已存在
        User userByName = userDao.findByUserName(user.getUsername());
        //或 if (!ObjectUtils.isEmpty(userByName))  对象不为空
        if (userByName!=null){
            //用户存在，比对密码
            if (userByName.getPassword().equals(user.getPassword())){
                return userByName;
            }else {
                throw new RuntimeException("密码不正确！");
            }
        }else {
            throw new RuntimeException("用户不存在！");
        }

    }
}
